import { Dep } from './Dep'

export function observer (obj, cb) {
  Object.keys(obj).forEach((key) => defineReactive(obj, key, obj[key], cb))
}

export function defineReactive (obj, key, val, cb) {
  const dep = new Dep()
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: () => {
      if (Dep.target) {
        dep.add(Dep.target)
      }
      return val
    },
    set: newVal => {
      if (newVal === val) return
      val = newVal
      dep.notify()
    }
  })
}
